package com.cuit.mimall.controller.frontend;

import com.cuit.mimall.common.R;
import com.cuit.mimall.dto.OrderDto;
import com.cuit.mimall.entity.Order;
import com.cuit.mimall.entity.OrderItem;
import com.cuit.mimall.service.IOrderService;
import com.cuit.mimall.service.IUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author TeaWu
 * @folder 前台/订单
 */
@RestController("frontendOrderController")
@RequestMapping("/api/v1/frontend/order")
public class OrderController {

    private final IOrderService orderService;
    private final IUserService userService;

    public OrderController(IOrderService orderService, IUserService userService) {
        this.orderService = orderService;
        this.userService = userService;
    }

    /**
     * 提交订单
     *
     * @param orderDto 订单信息
     * @return 订单id
     */
    @PostMapping("/create")
    @PreAuthorize("hasAnyAuthority('ROLE_USER')")
    public R<?> create(@RequestBody OrderDto orderDto) {
        Long userId = userService.getCurrentUser().getUser().getUserId();
        orderDto.getOrder().setUserId(userId);
        orderDto.getOrder().setCreateTime(LocalDateTime.now());
        Order order = orderDto.getOrder();
        List<OrderItem> items = orderDto.getItems();
        return orderService.addOrder(order, items);
    }

    /**
     * 分页获取用户的订单列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @return 订单列表
     * TODO
     */
    @GetMapping("/getOrders")
    @PreAuthorize("hasAnyAuthority('ROLE_USER')")
    public R<?> getOrders(@RequestParam(defaultValue = "1") Integer pageNum,
                          @RequestParam(defaultValue = "10") Integer pageSize) {
        Long userId = userService.getCurrentUser().getUser().getUserId();
        return orderService.getOrders(userId, pageNum, pageSize);
    }

    /**
     * 用户删除自己的订单
     *
     * @param orderId 订单id
     * @return 删除结果
     */
    @PutMapping("/deleteOrder")
    @PreAuthorize("hasAnyAuthority('ROLE_USER')")
    public R<?> deleteOrder(@RequestParam Long orderId) {
        return orderService.deleteOrder(orderId);
    }

    /**
     * 用户支付订单
     *
     * @param orderId 订单id
     * @return 支付结果
     */
    @PutMapping("/payOrder")
    @PreAuthorize("hasAnyAuthority('ROLE_USER')")
    public R<?> payOrder(@RequestParam Long orderId) {
        return orderService.payOrder(orderId);
    }
}
